using Autofac;
using Autofac.Extensions.DependencyInjection;
using EagCentralPlatform.Net8.Filter;
using EagCentralPlatform.Net8.StarpupModule;
using KL.Core.Common.HttpContextUser;
using KL.Core.Common.infrastructure;
using KL.Core.Common.MyOptions;
using KL.Core.Extensions;
using KL.Core.Extensions.Auth;
using KL.Core.Extensions.Cache;
using KL.Core.Extensions.Cors;
using KL.Core.Extensions.Log;
using KL.Core.Extensions.Mapper;
using KL.Core.Extensions.MinIO;
using KL.Core.Extensions.MongoDB;
using KL.Core.Extensions.MQ;
using KL.Core.Extensions.Options;
using KL.Standard.Core.Converter;
using KL.Standard.Model.Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Newtonsoft.Json;
using Serilog;
using Serilog.Events;

var builder = WebApplication.CreateBuilder(args);
builder.Host
    .UseServiceProviderFactory(new AutofacServiceProviderFactory())
    .ConfigureContainer<ContainerBuilder>(innerBuilder =>
    {
        innerBuilder.RegisterModule(new AutofacModuleRegister(builder.Configuration));
        innerBuilder.RegisterModule<AutofacPropertityModuleReg>();
    })
    .ConfigureAppConfiguration((hostingContext, config) =>
    {
        hostingContext.Configuration.ConfigureApplication();
    })
    ;

builder.ConfigureApplication();
// Add services to the container.

builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
builder.Services.AddControllers(o =>
{
    o.Filters.Add(typeof(GlobalExceptionFilter));
}).AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.ContractResolver = new KLJsonContractResolver();
        options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
        //options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
        options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
    }
);;
builder.Services.Configure<ApiBehaviorOptions>(options => options.SuppressModelStateInvalidFilter = true);
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddAutoMapper(typeof(AutoMapperConfig));
AutoMapperConfig.RegisterMappings();
builder.Services.AddScoped(typeof(LogFilterAttribute));
// 配置
builder.Services.AddSingleton(new AppSettings(builder.Configuration));
builder.Services.AddAllOptionRegister();
// Cors
builder.Services.AddCorsSetup();
// 缓存
builder.Services.AddCacheSetup();
// RabbitMQ
builder.Services.AddRabbitMqSetup();
// MinIO
builder.Services.AddMinIOSetup(builder.Configuration);
// MongoDB
builder.Services.AddMongoDbSetup(builder.Configuration);
// ORM
//builder.Services.AddSqlsugarSetup();
// JWT

JwtConfigOptions jwtConfig = builder.Configuration.GetSection("JwtConfig").Get<JwtConfigOptions>();
builder.Services.AddAuthentication_JWTSetup(jwtConfig);
// builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
//     .AddJwtBearer(options =>
//     {
//         options.TokenValidationParameters = new TokenValidationParameters
//         {
//             ValidateIssuer = true,
//             ValidateAudience = true,
//             ValidateLifetime = true,
//             ValidateIssuerSigningKey = true,
//
//             ValidIssuer = "Blog.Core",
//             ValidAudience = "wr",
//             IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("sdfsdfsrty45634kkhllghtdgdfss345t678fs"))
//         };
//     });
builder.Services.AddAuthorizationSetup(jwtConfig);
// builder.Services.AddAuthorization(options =>
// {
//     options.AddPolicy("Client", policy => policy.RequireClaim("iss", "Blog.Core").Build());
//     options.AddPolicy("SuperAdmin", policy => policy.RequireRole("SuperAdmin").Build());
//     options.AddPolicy("SystemOrAdmin", policy => policy.RequireRole("SuperAdmin", "System"));
//
//     options.AddPolicy("Permission", policy => policy.Requirements.Add(new PermissionRequirement()));
// });
// builder.Services.AddScoped<IAuthorizationHandler, PermissionRequirementHandler>();
// builder.Services.AddSingleton(new PermissionRequirement());


builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddScoped<IUser, AspNetUser>();
builder.Services.AddScoped<CurUserInfo>();

// serilog
builder.Host.AddSerilogSetup(); 
// var loggerConfiguration = new LoggerConfiguration()
//         .ReadFrom.Configuration(AppSettings.Configuration)
//         //.MinimumLevel.Information()
//         //.Enrich.FromLogContext()
//         //输出到控制台
//         .WriteTo.Console()
//         //将日志保存到文件中
//         .WriteTo.File("logs/GlobalInfoLogs_.log", 
//             restrictedToMinimumLevel: LogEventLevel.Information,
//             outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
//             rollingInterval: RollingInterval.Day)
//         .WriteTo.File("logs/GlobalExceptionLogs_.log", 
//             restrictedToMinimumLevel: LogEventLevel.Error,
//             outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
//             rollingInterval: RollingInterval.Day)
//     ;
// Log.Logger = loggerConfiguration.CreateLogger();
// builder.Host
//     .UseSerilog()
//     .ConfigureLogging(logging =>
//     {
//         logging.ClearProviders(); // 清除默认的日志提供程序
//         // logging.AddFilter("System", LogLevel.Error);
//         // logging.AddFilter("Microsoft", LogLevel.Error);
//         logging.AddSerilog(); // 添加 Serilog 日志提供程序
//     });;


var app = builder.Build();
app.ConfigureApplication();
app.UseApplicationSetup();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

//app.UseAuthorization();


app.MapControllers();

app.Run();